import { useLookup } from '@/utils/hooks/useLookup';
import type { FormDataDto } from '@/api/avic/demo/DemoMainNestFlowApi'; // 引入模块DTO
import {
  // getDemoMainNest,
  saveDemoMainNest,
  checkDemoUniqueUnique,
  saveFormAndStartProcess
} from '@/api/avic/demo/DemoMainNestFlowApi'; // 引入模块API
import { createEditor } from '@wangeditor/editor'; // 引入富文本依赖
import { useRichText } from '@/utils/hooks/useRichText'; // 引入富文本相关配置及方法
import {
  default as flowUtils,
  startFlowByFormCode,
  closeFlowLoading,
  openFlowDetail,
  getFieldAuth,
  getFieldVisible,
  getFieldDisabled,
  getFieldRequired
} from '@/views/avic/bpm/bpmutils/FlowUtils.js';
export const emits = ['reloadData', 'close'];
export function useDemoMainNestForm({ props, emit }) {
  const { proxy } = getCurrentInstance();
  const form = ref<FormDataDto>({
    id: '',
    formStep1: {},
    formStep2: {},
    formStep3: {}
  });
  const demoMainNestStep1 = ref();
  const demoMainNestStep2 = ref();
  const demoMainNestStep3 = ref();
  const formRef = ref(null);
  const formStep1Ref = ref(null);
  const formStep2Ref = ref(null);
  const formStep3Ref = ref(null);
  const formCode = 'DemoMainNestFormFlow';
  const openType = ref('add'); // 流程表单的打开方式，add:流程中心打开, edit: 待办打开
  const bpmParams = ref<any>({}); // 存储来自prop或者url的参数信息
  const bpmButtonParams = ref<any>({}); // 提交按钮传递的参数
  const bpmResult = ref(null); // 表单驱动方式启动流程的流程数据
  const authJson = ref(null);
  const rulesStep1: Record<string, Rule[]> = {
    demoUserId: [{ required: true, message: '用户不能为空', trigger: 'change' }],
    secretLevel: [{ required: true, message: '密级不能为空', trigger: 'change' }]
  };
  const rulesStep2: Record<string, Rule[]> = {
    demoNotnull: [{ required: true, message: '必填不能为空', trigger: 'change' }]
  };
  const rulesStep3: Record<string, Rule[]> = {
    demoUnique: [
      { required: true, message: '唯一值不能为空', trigger: 'change' },
      { validator: (rule, value) => validateDemoUniqueUnique(rule, value), trigger: 'blur' }
    ]
  };
  const layout = {
    labelCol: { flex: '0 0 140px' },
    wrapperCol: { flex: '1 1 0' }
  };
  const colLayout = proxy.$colLayout2; // 调用布局公共方法
  const loading = ref(false);
  const uploadFile = ref(null); // 附件ref
  const autoCode = ref(null); // 自动编码ref
  const { lookupList } = useLookup(['PLATFORM_SEX', 'PLATFORM_CHECK_TYPE', 'PLATFORM_DEGREE']);
  const richtextDetail = ref(null); // 富文本ref
  const editorRef = shallowRef(null); // 编辑器实例，必须用 shallowRef
  const { toolbarConfig, editorConfig, onCreated, dealRichText, convertImageSrc } = useRichText(
    editorRef,
    'demoMainNestDemoRichtext',
    'DEMO_MAIN_NEST'
  );

  const currentStep = ref(0); // 当前向导步骤
  const steps = [
    { id: 'step1', title: '步骤一' },
    { id: 'step2', title: '步骤二' },
    { id: 'step3', title: '步骤三' }
  ];
  const stepDescribe = [
    '步骤一：创建采购订单首先选择采购类型，上传相应的采购依据附件',
    '步骤二：根据采购依据(请购单/采购计划)内容勾选相应需要采购的物料明细',
    '步骤三：为订单选择或填写合适的条款'
  ];

  if (props.params) {
    bpmParams.value = props.params;
  } else {
    if (proxy.$route) {
      bpmParams.value = proxy.$route.query;
    }
  }
  if (bpmParams.value) {
    // 加载流程数据
    form.value.id = bpmParams.value.id;
    openType.value = bpmParams.value.id ? 'edit' : 'add';
  }

  onMounted(() => {
    if (props.formId) {
      // 编辑、详情页面加载数据
      getFormData(props.formId);
    }
  });
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  });

  /**
   * 编辑、详情页面加载数据
   * @param {String} id 行数据的id
   */
  async function getFormData(id) {
    // 示例数据
    console.log('id', id);
    form.value.id = '111111';
    form.value.formStep1 = {
      demoUserId: '8a69ef448c325404018c32a5818b01c3',
      demoUserIdAlias: '多啦爱梦(undefined)',
      secretLevel: '1',
      demoRadio: '2',
      demoCheckbox: '1;2',
      demoRadioButton: '2',
      demoSelect: '001',
      demoSwitch: 'N'
    };
    form.value.formStep2 = {
      demoNotnull: 'gtest',
      demoCode: null
    };
    form.value.formStep3 = {
      demoUnique: 'test',
      demoRichtext: '<p>test</p>'
    };
    form.value.formStep1.demoCheckbox = form.value.formStep1.demoCheckbox?.toString()?.split(';'); // 处理复选框数据
    form.value.formStep1.demoSelectMultiple = form.value.formStep1.demoSelectMultiple?.toString()?.split(';'); // 处理多选下拉数据

    // 处理富文本
    await dealRichText(form.value.formStep3.demoRichtext);
    // 详情表单 富文本是否可编辑
    if (fieldDisabled('demoRichtext')) {
      editorRef.value.disable();
    }

    // loading.value = true;
    // getDemoMainNest(id)
    //   .then(async (res) => {
    //     if (res.success) {
    //       form.value.id = res.data.id;
    //       form.value.formStep1 = res.data.formStep1;
    //       form.value.formStep2 = res.data.formStep2;
    //       form.value.formStep3 = res.data.formStep3;
    //       form.value.formStep1.demoCheckbox = form.value.formStep1.demoCheckbox?.toString()?.split(';'); // 处理复选框数据
    //       form.value.formStep1.demoSelectMultiple = form.value.formStep1.demoSelectMultiple?.toString()?.split(';'); // 处理多选下拉数据
    //       // 处理富文本
    //       await dealRichText(form.value.formStep3.demoRichtext);
    //       // 详情表单 富文本不可编辑
    //       if (richtextDetail.value !== null) {
    //         editorRef.value.disable();
    //       }
    //       loading.value = false;
    //     }
    //   })
    //   .catch(() => {
    //     proxy.$message.warning('获取表单数据失败！');
    //     loading.value = false;
    //   });
  }

  /** 保存 */
  function saveForm() {
    // case 1. 表单+表格
    // demoMainNestStep3.value.formStep3Ref.validate().then(() => { // 表单
    //   demoMainNestStep3.value.validate((validate) => { // 表格，行编辑表格校验方法需在最后一步vue文件中定义并暴露
    //     if (!validate) {
    //       return;
    //     }
    //     // 附件密级校验 先判断
    //     // ...
    //   });
    // });
    // case 2. 仅表格
    // demoMainNestStep3.value.validate((validate) => { // 行编辑表格校验方法需在最后一步vue文件中定义并暴露
    //   if (!validate) {
    //     return;
    //   }
    //   // 附件密级校验 先判断
    //   // ...
    // });
    // case 3. 仅表单
    demoMainNestStep3.value.formStep3Ref
      .validate()
      .then(() => {
        // 附件密级校验 先判断
        const errorMessage = demoMainNestStep3.value.uploadFile.validateUploaderFileSecret(form.value.formStep1.secretLevel);
        if (errorMessage) {
          return;
        }
        loading.value = true;
        const subInfoList = demoMainNestStep2.value.getChangedData(); // 获取子表数据
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value);
        postData.formStep1.demoCheckbox = postData.formStep1.demoCheckbox?.join(';'); // 处理复选框数据
        postData.formStep1.demoSelectMultiple = postData.formStep1.demoSelectMultiple?.join(';'); // 处理多选下拉数据
        postData.formStep1.demoSwitch = postData.formStep1.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
        postData.formStep2.demoSubNestList = subInfoList; // 挂载子表数据
        if (demoMainNestStep2.value.autoCode) {
          // 获取编码码段值
          postData.formStep2.demoCode = demoMainNestStep2.value.autoCode.getSegmentValue();
        }
        // 处理富文本
        const editorHtmljsonCopy = proxy.$lodash.cloneDeep(demoMainNestStep3.value.editorRef.children);
        convertImageSrc(editorHtmljsonCopy);
        const newEditor = createEditor({ content: editorHtmljsonCopy });
        const newEditorHtml = newEditor.getHtml();
        postData.formStep3.demoRichtext = newEditorHtml;
        // 发送请求
        saveDemoMainNest(postData)
          .then((res) => {
            if (res.success) {
              demoMainNestStep3.value.uploadFile.upload(form.value.id || res.data.formStep3); // 附件上传
            } else {
              loading.value = false;
            }
          })
          .catch(() => {
            loading.value = false;
          });
      })
      .catch((error) => {
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep3.value.formStep3Ref, error);
      });
  }
  async function saveAndStartProcess(params) {
    demoMainNestStep3.value.formStep3Ref
      .validate()
      .then(() => {
        const errorMessage = demoMainNestStep3.value.uploadFile.validateUploaderFileSecret(form.value.formStep1.secretLevel);
        if (errorMessage) {
          return;
        }
        loading.value = true;
        const subInfoList = demoMainNestStep2.value.getChangedData(); // 获取子表数据
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value);
        postData.formStep1.demoCheckbox = postData.formStep1.demoCheckbox?.join(';'); // 处理复选框数据
        postData.formStep1.demoSelectMultiple = postData.formStep1.demoSelectMultiple?.join(';'); // 处理多选下拉数据
        postData.formStep1.demoSwitch = postData.formStep1.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
        postData.formStep2.demoSubNestList = subInfoList; // 挂载子表数据
        if (demoMainNestStep2.value.autoCode) {
          // 获取编码码段值
          postData.formStep2.demoCode = demoMainNestStep2.value.autoCode.getSegmentValue();
        }
        // 处理富文本
        const editorHtmljsonCopy = proxy.$lodash.cloneDeep(demoMainNestStep3.value.editorRef.children);
        convertImageSrc(editorHtmljsonCopy);
        const newEditor = createEditor({ content: editorHtmljsonCopy });
        const newEditorHtml = newEditor.getHtml();
        postData.formStep3.demoRichtext = newEditorHtml;

        // 点击保存并启动流程按钮触发
        if (!props.bpmInstanceObject && !params.dbid) {
          // 校验表单并选择需要启动的流程模板
          getBpmDefine(postData);
        } else {
          const param = {
            processDefId: params.dbid || bpmParams.value.defineId,
            formCode,
            postData
          };
          // 发送请求
          saveFormAndStartProcess(param)
            .then((res) => {
              if (res.success) {
                if (props.bpmInstanceObject) {
                  bpmButtonParams.value = { params, result: res.data };
                }
                bpmResult.value = res.data;
                if (!form.value.id) {
                  form.value.id = res.data.formId;
                }
                uploadFile.value.upload(form.value.id || res.data); // 附件上传
              } else {
                errorCallback();
              }
            })
            .catch(() => {
              errorCallback();
            });
        }
      })
      .catch((error) => {
        closeFlowLoading(props.bpmInstanceObject);
        loading.value = false;
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(formRef, error);
      });
  }
  /** 校验通过后，读取要启动的流程模板 */
  function getBpmDefine(formData) {
    startFlowByFormCode({
      formCode,
      formData,
      callback: (bpmDefinedInfo) => {
        if (!bpmDefinedInfo) {
          loading.value = false;
        } else {
          saveAndStartProcess(bpmDefinedInfo);
        }
      }
    });
  }
  /** 保存步骤一 */
  async function saveFormStep1() {
    let result = true;
    result = await demoMainNestStep1.value.formStep1Ref
      .validate()
      .then(() => {
        loading.value = true;
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value.formStep1);
        postData.demoCheckbox = postData.demoCheckbox?.join(';'); // 处理复选框数据
        postData.demoSelectMultiple = postData.demoSelectMultiple?.join(';'); // 处理多选下拉数据
        postData.demoSwitch = postData.demoSwitch === 'Y' ? 'Y' : 'N'; // 处理开关
        // 调用保存接口示例
        // saveDemoMainNest(postData)
        //   .then((res) => {
        //     if (res.success) {
        //       proxy.$message.success('保存成功！');
        //       return true;
        //     }
        //     proxy.$message.error('当前步骤保存失败！');
        //     loading.value = false;
        //     return false;
        //   })
        //   .catch(() => {
        //     loading.value = false;
        //     return false;
        //   });
        proxy.$message.success('保存成功！'); // 此行演示用，需删除
        loading.value = false; // 此行演示用，需删除
        return true; // 此行演示用，需删除
      })
      .catch((error) => {
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep1.value.formStep1Ref, error);
        return false;
      });
    return result;
  }
  /** 保存、保存并启动流程处理成功后的逻辑 */
  function successCallback() {
    if (props.bpmInstanceObject) {
      closeFlowLoading(props.bpmInstanceObject);
      // 刷新表单版本
      getFormData(form.value.id);
      // 回调选人等流程按钮事件
      if (bpmButtonParams.value.params.callback) {
        bpmButtonParams.value.params.callback(bpmButtonParams.value.result);
        bpmButtonParams.value = {};
      }
    } else {
      // 添加页面-保存并启动流程后，打开流程详情页
      if (bpmResult.value) {
        openFlowDetail(bpmResult.value, props.bpmOperatorRefresh);
      }
      proxy.$message.success('保存成功！');
      emit('reloadData');
      emit('close');
    }
  }
  /** 数据保存失败的回调 */
  function errorCallback() {
    if (props.bpmInstanceObject) {
      closeFlowLoading(props.bpmInstanceObject);
    } else {
      loading.value = false;
    }
  }
  /** 附件上传完之后的回调函数 */
  function afterUploadEvent(_successFile, errorFile) {
    if (errorFile.length > 0) {
      errorCallback();
      // 有附件保存失败的处理
      proxy.$message.error('附件保存失败！');
    } else {
      // 所有附件都保存成功的处理
      proxy.$message.success('保存成功！');
    }
    // 仅在最后一步才关闭弹窗
    if (currentStep.value === steps.length - 1) {
      // 所有附件都保存成功的处理
      successCallback();
    }
  }
  /** 异步校验唯一值唯一 */
  async function validateDemoUniqueUnique(_rule, value) {
    if (value) {
      const res = await checkDemoUniqueUnique({
        demoUnique: value,
        id: props.formId || ''
      });
      if (res.success) {
        if (res.data) {
          return Promise.resolve();
        }
        return Promise.reject('唯一值已存在!');
      }
      return Promise.reject('唯一值唯一性校验失败!');
    }
    return Promise.resolve();
  }
  /** 返回关闭事件 */
  function closeModal() {
    emit('close');
  }

  /** 表单字段是否必填 */
  function fieldRequiredStep1(fieldName) {
    if (!props.bpmInstanceObject) {
      // 由于抽屉详细页面和流程详情页面公用一套页面，这里需要模拟详细页面字段的必填校验为非必填
      rulesStep1.value = [];
      return rulesStep1;
    }
    checkAuthJson();
    // 由于最近代码会合为一套这里写死第一步的rules
    return getFieldRequired(authJson.value, fieldName, rulesStep1, props.bpmInstanceObject);
  }
  function fieldRequiredStep2(fieldName) {
    if (!props.bpmInstanceObject) {
      // 由于抽屉详细页面和流程详情页面公用一套页面，这里需要模拟详细页面字段的必填校验为非必填
      rulesStep2.value = [];
      return rulesStep2;
    }
    checkAuthJson();
    // 由于最近代码会合为一套这里写死第一步的rules
    return getFieldRequired(authJson.value, fieldName, rulesStep2, props.bpmInstanceObject);
  }
  function fieldRequiredStep3(fieldName) {
    if (!props.bpmInstanceObject) {
      // 由于抽屉详细页面和流程详情页面公用一套页面，这里需要模拟详细页面字段的必填校验为非必填
      rulesStep3.value = [];
      return rulesStep3;
    }
    checkAuthJson();
    // 由于最近代码会合为一套这里写死第一步的rules
    return getFieldRequired(authJson.value, fieldName, rulesStep3, props.bpmInstanceObject);
  }
  /** 表单字段是否显示 */
  function fieldVisible(fieldName) {
    if (!props.bpmInstanceObject) {
      // 由于抽屉详细页面和流程详情页面公用一套页面，这里需要模拟详细页面字段的显示为true
      return true;
    }
    checkAuthJson();
    return getFieldVisible(authJson.value, fieldName);
  }
  /** 表单字段是否可编辑 */
  function fieldDisabled(fieldName) {
    if (!props.bpmInstanceObject) {
      // 由于抽屉详细页面和流程详情页面公用一套页面，这里需要模拟详细页面字段的禁用为true
      return true;
    }
    checkAuthJson();
    return getFieldDisabled(authJson.value, fieldName, props.bpmInstanceObject);
  }
  /** 表单附件是否必填(按elementId) */
  function attachmentRequired(fieldName) {
    const res = flowUtils.attachmentRequired(props.bpmInstanceObject, fieldName);
    return res;
  }
  function checkAuthJson() {
    if (authJson.value == null) {
      authJson.value = getFieldAuth(props.bpmInstanceObject);
    }
  }
  /** 点击流程按钮的前置事件 */
  function beforeClickBpmButtons() {
    return new Promise((resolve) => {
      resolve(true);
    });
  }
  /** 点击流程按钮的后置事件 */
  function afterClickBpmButtons() {
    return new Promise((resolve) => {
      resolve(true);
    });
  }
  /** 流程查看 */
  function showProcess() {
    flowUtils.detailByOptions({
      formId: form.value.id,
      bpmOperatorRefresh: getFormData
    });
  }
  /** 刷新事件 */
  function reloadData() {
    emit('reloadData');
  }
  /** 步骤跳转 */
  async function onNextStep(step) {
    if (step > 1) {
      return;
    }
    let result = true; // 校验状态（校验失败时会置为false）

    // 步骤一：单独保存按钮 + 下一步并保存
    if (currentStep.value === 0 && step > 0) {
      result = await saveFormStep1();
    }

    // 步骤二： 仅下一步，无保存操作
    if (currentStep.value === 1 && step > 0) {
      // 子表数据校验
      demoMainNestStep2.value.validate((validate) => {
        if (!validate) {
          result = false;
        }
      });
      try {
        await demoMainNestStep2.value.formStep2Ref.validate();
      } catch (e) {
        result = false;
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(demoMainNestStep2.value.formStep2Ref, e);
      }
    }
    // 校验失败
    if (!result) return;
    currentStep.value += step;
  }
  return {
    proxy,
    currentStep,
    steps,
    stepDescribe,
    form,
    formRef,
    formStep1Ref,
    formStep2Ref,
    formStep3Ref,
    rulesStep1,
    rulesStep2,
    rulesStep3,
    layout,
    colLayout,
    loading,
    lookupList,
    uploadFile,
    afterUploadEvent,
    autoCode,
    richtextDetail,
    toolbarConfig,
    editorConfig,
    editorRef,
    onCreated,
    saveForm,
    saveAndStartProcess,
    showProcess,
    saveFormStep1,
    closeModal,
    reloadData,
    beforeClickBpmButtons,
    afterClickBpmButtons,
    attachmentRequired,
    checkAuthJson,
    fieldVisible,
    fieldDisabled,
    fieldRequiredStep1,
    fieldRequiredStep2,
    fieldRequiredStep3,
    onNextStep,
    demoMainNestStep1,
    demoMainNestStep2,
    demoMainNestStep3
  };
}
